package com.wu.foodsafetyplayer.widget;

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.ContentObserver;
import android.os.Handler;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.TextView;

import com.wu.foodsafetyplayer.R;
import com.wu.foodsafetyplayer.http.Func;

import java.util.Calendar;

/**
 * Like AnalogClock, but digital. Shows seconds.
 */
public class DigitalClock extends TextView {
	// FIXME: implement separate views for hours/minutes/seconds, so
	// proportional fonts don't shake rendering

	Calendar mCalendar;
	// private final static String m12 ="h:mm aa";// "h:mm:ss aa"
	private String m24 = "HH:mm";// "k:mm:ss"
	// @SuppressWarnings("FieldCanBeLocal") // We must keep a reference to this
	// observer
	private FormatChangeObserver mFormatChangeObserver;

	private Runnable mTicker;

	private boolean mTickerStopped = false;

	String mFormat;

	public DigitalClock(Context context) {
		super(context);
		initAttributes(context, null);
		initClock();
	}

	public DigitalClock(Context context, AttributeSet attrs) {
		super(context, attrs);
		initAttributes(context, attrs);
		initClock();
	}

	protected TypedArray getTypedArray(Context context,
			AttributeSet attributeSet, int[] attr) {
		return context.obtainStyledAttributes(attributeSet, attr, 0, 0);
	}

	private void initAttributes(Context context, AttributeSet attributeSet) {
		TypedArray attr = getTypedArray(context, attributeSet, R.styleable.DigitalClock);

		if (attr == null) {
			return;
		}
		try {
			m24 = attr.getString(R.styleable.DigitalClock_dc_format);
		} finally {
			attr.recycle();
		}
	}

	private void initClock() {
		// setTypeface(CloudMediaTextViewTypeface.SIMPLIFIEDSTYLE);
		if (mCalendar == null) {
			mCalendar = Calendar.getInstance();
		}

		mFormatChangeObserver = new FormatChangeObserver();
		getContext().getContentResolver().registerContentObserver(
				Settings.System.CONTENT_URI, true, mFormatChangeObserver);

		setFormat();
	}

	String oldTime = "";

	@Override
	protected void onAttachedToWindow() {
		mTickerStopped = false;
		super.onAttachedToWindow();

		Func.FUNC_TASK.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				while (true) {
					try {
						mCalendar.setTimeInMillis(System.currentTimeMillis());
						final String time = DateFormat.format(mFormat,
								mCalendar).toString();
						if (!oldTime.equals(time)) {
							oldTime = time;
							mHandler.sendEmptyMessage(0);
						}

						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
		});
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		mTickerStopped = true;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			setText(oldTime);
		};
	};

	/**
	 * Pulls 12/24 mode from system settings
	 */
	private boolean get24HourMode() {
		return DateFormat.is24HourFormat(getContext());
	}

	private void setFormat() {
		if (get24HourMode()) {
			mFormat = m24;
		} else {
			mFormat = m24;
		}
	}

	private class FormatChangeObserver extends ContentObserver {
		public FormatChangeObserver() {
			super(new Handler());
		}

		@Override
		public void onChange(boolean selfChange) {
			setFormat();
		}
	}

	@Override
	public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
		super.onInitializeAccessibilityEvent(event);
		// noinspection deprecation
		event.setClassName(DigitalClock.class.getName());
	}

	@SuppressLint("NewApi")
	@Override
	public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
		super.onInitializeAccessibilityNodeInfo(info);
		// noinspection deprecation
		info.setClassName(DigitalClock.class.getName());
	}
}
